package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"myNote/database"
	"myNote/models"
)


func SafeCheck(context *gin.Context)  {
	safeKey := context.DefaultQuery("safeKey","")
	if safeKey == ""{
		if _,err := context.Cookie("sessionId");err != nil{
			context.JSON(500,gin.H{"code":500,"data":nil,"msg":"未授权请求"})
			context.Abort()
		}else {
			var session  = models.Session{}
			sessionid,_ := context.Cookie("sessionId")
			database.DB.Find(&session,"session_id = ?",sessionid)
			if session.ID == 0{
				context.JSON(500,gin.H{"code":500,"data":nil,"msg":"未授权请求"})
				context.Abort()
			}else{
				context.Set("userId",fmt.Sprintf("%d",session.UserId))
				context.Next()
			}
		}
	}else{
		if safeKey == "de38fba6afd03eec07b8bad39728719d6b4131f2"{
			userId := context.DefaultQuery("sessionId",fmt.Sprintf("%s",uuid.Must(uuid.NewV4(),nil)))
			context.SetCookie("sessionId",userId,31536000,"/","121.199.52.114",false,false)
			context.JSON(200,gin.H{"code":200,"msg":"成功"})
			context.Abort()
		}else{
			context.JSON(500,gin.H{"code":500,"data":nil,"msg":"未授权请求"})
			context.Abort()
		}
	}
}
